<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>侧边栏固定</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        .header,
        .banner,
        .footer {
            width: 1200px;
            margin: 0 auto;
            margin-top: 20px;
        }

        .header {
            height: 300px;
            background: skyblue;
        }

        .banner {
            height: 400px;
            background: rgb(209, 83, 160);
        }

        .footer {
            height: 800px;
            background: greenyellow;
        }

        .slide {
            width: 40px;
            height: 120px;
            background: -webkit-linear-gradient(top, rgb(212, 97, 116), rgb(227, 207, 52));
            position: absolute;
            top: 450px;
            right: 0px;
            text-align: center;
        }

        .return1 {
            position: absolute;
            bottom: 0px;
            display: none;
        }
    </style>
</head>

<body>
    <div class="header">头部信息</div>
    <div class="banner">主体信息</div>
    <div class="footer">底部信息</div>
    <div class="slide">侧边栏
        <p class="return1">返回顶部</p>
    </div>
    <script>
        let header = document.querySelector('.header');
        let banner = document.querySelector('.banner');
        let footer = document.querySelector('.footer');
        let slide = document.querySelector('.slide');
        let return1 = document.querySelector('.return1');

        let differ = slide.offsetTop - banner.offsetTop;
        // console.log(differ);
        window.addEventListener('scroll', function () {
            if (window.pageYOffset >= banner.offsetTop) {
                slide.style.position = 'fixed';
                slide.style.top = differ + 'px';
            } else {
                slide.style.position = 'absolute';
                slide.style.top = 450 + 'px';
            }
            if(window.pageYOffset >= footer.offsetTop){
                return1.style.display = 'block';
            }else{
                return1.style.display = 'none';
            }
        });
    </script>
</body>

</html>